/*
 * @Author       : wfl
 * @LastEditors: root zhangpengpeng@ikingtech.com
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-10-31 11:13:02
 * @LastEditTime: 2024-03-22 19:43:06
 */
import { defineStore } from 'pinia'
import { loginApi } from '@/api/user'

import { passwordEncry } from 'iking-utils'

const TokenKey = import.meta.env.VITE_DATAV_TOKEN_KEY
export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    name: '',
    avatar: '',
    role: -1,
    user: null,
    id:'',
    imgUrl:'',
  }),
  actions: {
    async login(param) {
      const res = await loginApi.login({
        credentialName: param.username,
        password: passwordEncry(
          param.password || '',
          '1234567890000000',
          {
            encode: 'hex',
          },
        ).AES.encrypt(),
      },
      {
        'X-PASSWORD-ENCRYPT': 'encrypt',
      })
      if (res?.success) {
        this.token = res.data.token
        this.id = res.data.id
        localStorage.setItem('userId', res.data.id)
        localStorage.setItem(TokenKey, res.data.token)
        loginApi.setAuthGrant()
      }
      return res
    },
    async getUserInfo() {
      try {
        const res = await loginApi.getUserInfo(localStorage.getItem('userId') )
        if (res.success) {
          const data = res.data
          this.name = data.name
          this.avatar = data.avatar ? data.avatar : `${this.imgUrl}/datav/file/system/default-avatar.png`
          this.role = 1
          this.user = data
        } else {
          throw error
        }
      } catch (error) {
        throw error
      }
    },
    resetToken() {
      this.token = ''
      localStorage.removeItem(TokenKey)
    },
    isLogin() {
      const token = localStorage.getItem(TokenKey)
      return !!token
    },
    async logout() {
      const res = await loginApi.loginOut()
      if (res.success)
        this.resetToken()
      else
        throw Error(res.msg)
    },
  },
})
